package com.moss.cloud.common.core.utils;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 随机ID字符串付不是ID生成工具
 *
 * @author 瑾年
 * @data 2019/4/11
 */
public class GenUtil {
    private static MossSnowFlake SNOW_FLAKE = new MossSnowFlake();
    /**
     * 定义常量
     */
    public static String[] CHARS = new String[]{"a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};
    /**
     * 定义常量
     */
    private static String STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 生成8位随机字符串
     *
     * @return
     */
    public static String strNo() {
        StringBuilder shortBuffer = new StringBuilder();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(CHARS[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

    /**
     * 生成四位随机字符串
     *
     * @return
     */
    public static String code() {
        StringBuilder sb = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            char ch = STR.charAt(new Random().nextInt(STR.length()));
            sb.append(ch);
        }
        return sb.toString();
    }

    /**
     * 生成六位随机临时码
     *
     * @return
     */
    public static String randomCode() {
        int codeLength = 6;
        StringBuilder randomCode = new StringBuilder();
        for (int i = 0; i < codeLength; i++) {
            int randomDigit = ThreadLocalRandom.current().nextInt(10);
            randomCode.append(randomDigit);
        }
        return randomCode.toString();
    }

    public static String getUUID() {
        String originalUUID = UUID.randomUUID().toString();
        return originalUUID.replace("-", "");
    }

    /**
     * 使用机器IP和workerId快捷生成分布式ID
     *
     * @return
     */
    public static Long nextId() {
        return SNOW_FLAKE.nextId();
    }

    /**
     * 使用机器IP和workerId快捷生成分布式ID-string类型
     *
     * @return
     */
    public static String nextStrId() {
        return String.valueOf(SNOW_FLAKE.nextId());
    }

    public static void main(String[] args){
        for (int i = 0; i <10 ; i++) {
            System.out.println(getUUID());
        }

    }
}
